﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aho.PathEditor.Business.Entities;
using Microsoft.Win32;

namespace Aho.PathEditor.Business.Services.Path
{
    internal class RegistryReader : Aho.PathEditor.Business.Services.Path.IRegistryReader
    {
        public Entities.PathListEntity GetAllPaths()
        {
            PathListEntity newList = new PathListEntity();
            newList.AddRange(KeyPathForScope(PathScope.System));
            newList.AddRange(KeyPathForScope(PathScope.User));

            return newList;
        }

        private IEnumerable<PathEntity> KeyPathForScope(PathScope scope)
        {
            var keys = GetRegKeyValue(scope);
            if (keys != null)
            {
                return ListConvert(keys, scope);
            }
            else
            {
                return new List<PathEntity>(0);
            }
        }

        private IEnumerable<PathEntity> ListConvert(string path, PathScope scope)
        {
            List<PathEntity> newList = new List<PathEntity>();
            path.Split(';').ToList().ForEach(t => newList.Add(new PathEntity(t.ToString(), scope)));
            return newList; 
        }

        
        private string GetRegKeyValue(PathScope scope)
        {
            object key;
            string keyName = GetRegKeyFolder(scope);
            if (scope == PathScope.User)
            {
                key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyName).GetValue("Path");
            }
            else
            {
                key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(keyName).GetValue("Path");
            }
            return key == null ? null : key.ToString();
        }

        private string GetRegKeyFolder(PathScope scope)
        {
            //http://vlaurie.com/computers2/Articles/environment.htm
            string keyName;

            switch (scope)
            {
                case PathScope.System:
                    {
                        keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
                        break;
                    }
                case PathScope.User:
                    {
                        keyName = @"Environment";

                        break;
                    }
                default:
                    {
                        throw new ArgumentException("Scope can't be:" + scope.ToString());
                    }
            }
            return keyName;
        }


        public void SavePaths(PathListEntity pathEntityList)
        {
            Dictionary<PathScope, PathListEntity> listEntitys = EntityDictGetFromList(pathEntityList);
            foreach (var item in listEntitys)
            {
                SaveSetings(item.Key, item.Value);
            }
        }

        private void SaveSetings(PathScope pathScope, PathListEntity pathListEntity)
        {
            string regKeyname = GetRegKeyFolder(pathScope);
            StringBuilder sb = new StringBuilder();
            foreach (var item in pathListEntity)
            {
                if (item.Directory.Length>0)
                {
                    sb.Append(item.Directory);
                    sb.Append(";");
    
                }
            }
            sb.Remove(sb.Length - 1, 1);
            RegistryKey key;
            if (pathScope == PathScope.User)
            {
                key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(regKeyname,true);
            }
            else
            {
                key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKeyname,true);
            }
            
            key.SetValue("Path", sb.ToString());
        }
        
        private Dictionary<PathScope, PathListEntity> EntityDictGetFromList(PathListEntity pathEntityList)
        {
            Dictionary<PathScope, PathListEntity> newList = new Dictionary<PathScope, PathListEntity>();
                     
            var ret = from path in pathEntityList
                      group path by path.AccessScope into g
                      select g;
            

            foreach (var item in ret)
            {
                Console.WriteLine(item.Key);
                PathListEntity entitiList = new PathListEntity();
                foreach (var entity in item)
                {
                    entitiList.Add(entity);
                }
                newList.Add(item.Key, entitiList);
            }

            return newList;

        }
    }
}
